package com.master.rabbitmq;

import com.master.domain.MiaoshaOrder;
import com.master.domain.MiaoshaUser;
import com.master.redis.RedisServer;
import com.master.service.GoodsService;
import com.master.service.MiaoshaService;
import com.master.service.OrderService;
import com.master.util.CodeMsg;
import com.master.util.Result;
import com.master.vo.GoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//消费者
@Service
public class MQReceiver {

    private static Logger logger = LoggerFactory.getLogger(MQReceiver.class);

    @Autowired
    RedisServer redisServer;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    MiaoshaService miaoshaService;


    @RabbitListener(queues = MQConfig.MIAOSHA_QUEUE)
    public void receive(String message){
        logger.info(" miaosha_queue receive message:"+message);
        MiaoshaMessage mm = RedisServer.stringToBean(message,MiaoshaMessage.class);
        //从MiaoshaMessage中取得用户和商品信息
        MiaoshaUser user = mm.getUser();
        long goodsId = mm.getGoodsId();

        //先从数据库中查询库存
        GoodsVo goodsVo = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goodsVo.getStockCount();//获取的是秒杀商品的库存
        if (stock <= 0) {
            return;
        }
        //判断是否已经秒杀到了
        //查询秒杀订单,如果可以查询到对应的秒杀订单,则说明用户已经秒杀过了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId);
        if(order != null){
            return;
        }

        //秒杀的步骤
        //减库存,生成秒杀订单
        miaoshaService.miaosha(user,goodsVo);
    }


//    @RabbitListener(queues = MQConfig.QUEUE)
//    public void receive(String message){
//        logger.info("receive message:"+message);
//    }
//
//    @RabbitListener(queues = MQConfig.TOPIC_QUEUE1)
//    public void receiveTopic1(String message){
//        logger.info("receive message:"+message);
//    }
//
//    @RabbitListener(queues = MQConfig.TOPIC_QUEUE2)
//    public void receiveTopic2(String message){
//        logger.info("receive message:"+message);
//    }
//
//    @RabbitListener(queues = MQConfig.HEADERS_QUEUE)
//    public void receiveHeaderQueue(byte[] message){
//        logger.info(" headerQueue receive message:"+ new String(message));
// }





}
